package com.lunatic.rocketmq.controllelr;


import com.lunatic.rocketmq.model.DemoMessage;
import com.lunatic.rocketmq.service.ProducerService;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.UUID;

@RestController
@RequestMapping("/send")
public class RMQController {

    @Autowired
    private ProducerService producerService;

    /**
     * 普通发送消息
     *
     * @param message
     * @return
     */
    @GetMapping("/common")
    public String sendCommonMessage(@RequestParam(value = "message") String message) {
        DemoMessage demoMessage = new DemoMessage(
                UUID.randomUUID().toString(),
                message,
                LocalDateTime.now()
        );
        producerService.send(demoMessage);
        return "消息已发送";
    }


    /**
     * 同步发送消息
     *
     * @param message
     * @return
     */
    @GetMapping("/sync")
    public String sendSyncMessage(@RequestParam(value = "message") String message) {
        DemoMessage demoMessage = new DemoMessage(
                UUID.randomUUID().toString(),
                message,
                LocalDateTime.now()
        );
        String id = producerService.sendSyncMessage(demoMessage);
        return "同步发送成功，消息ID：" + id;
    }

    /**
     * 异步发送消息
     *
     * @param message
     * @return
     */
    @GetMapping("/async")
    public String sendAsyncMessage(@RequestParam(value = "message") String message) {
        DemoMessage demoMessage = new DemoMessage(
                UUID.randomUUID().toString(),
                message,
                LocalDateTime.now()
        );
        producerService.sendAsyncMessage(demoMessage);
        return "异步发送已触发";
    }

    /**
     * 发送事务消息
     *
     * @param message
     * @return
     */
    @GetMapping("/tx")
    public String sendTransactionMessage(@RequestParam(value = "message") String message) {
        DemoMessage demoMessage = new DemoMessage(
                UUID.randomUUID().toString(),
                message,
                LocalDateTime.now()
        );
        LocalTransactionState status = producerService.sendTransactionMessage(demoMessage);
        return "事务消息状态：" + status;
    }

}
